﻿@namespace Masa.Blazor.Presets
@using Masa.Blazor.Presets.PageStack
@inherits MasaComponentBase
@inject NavigationManager NavigationManager

<PPageStackContainer Id="@Id"
                     Class="@GetClass()"
                     Style="@GetStyle()"
                     TabRules="@TabRules"
                     OnActiveTabUpdate="@OnActiveTabUpdate"
                     @attributes="@Attributes">
    @ChildContent
</PPageStackContainer>

<CascadingValue Value="this" IsFixed>
    @for (var i = 0; i < Pages.Count; i++)
    {
        var index = i;
        var pageData = Pages.ElementAt(index);
        var isTop = i == Pages.Count - 1;
        var shouldRender = isTop && NavigationManager.GetAbsolutePath().Equals(pageData.AbsolutePath, StringComparison.OrdinalIgnoreCase);

        /*
         * Even if shouldRender is false, ChildContent will be rendered on the first load.
         * At this point, ChildContent may contain content from the previous page,
         * causing unnecessary re-rendering.
         * Only when shouldRender is true, we can ensure ChildContent is from the current page
        */
        if (shouldRender)
        {
            // Control the actual content rendering in PPageStackItem component by setting ReadyToRender flag
            pageData.ReadyToRender = true;
        }

        <PPageStackItem AppBarVisible="@AppBarAlwaysVisible"
                        DisableUnderlaySlide="@DisableUnderlaySlide"
                        Data="pageData"
                        CanRender="@shouldRender"
                        OnGoBack="@HandleOnPrevious"
                        ChildContent="@ChildContent"
                        LoaderContent="@(LoaderContent ?? _defaultLoaderContent)"
                        @key="@pageData.Id">
        </PPageStackItem>
    }
</CascadingValue>

@code {

    private RenderFragment RenderDefaultLoader() => __builder =>
    {
        <MProgressCircular Indeterminate
                           Size="48"
                           Style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"/>
    };

}